package com.kkb.controller;

import com.kkb.vo.Team;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.List;

@Controller
public class RestfulController {

    private static List<Team> teamList;
    static{
        teamList = new ArrayList<>();
        for(int i=0;i<10;i++){
            Team team = new Team();
            team.setId(1001+i);
            team.setName("灰熊"+i);
            team.setLocation("孟菲斯");
            teamList.add(team);
        }
    }
    @RequestMapping("restful")
    public ModelAndView restful(){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("/restful");
        return modelAndView;
    }
    @RequestMapping(value = "/teams",method = RequestMethod.GET)
    @ResponseBody
    public List<Team> getTeamList(){
        return teamList;
    }
    @RequestMapping(value = "/team/{id}",method = RequestMethod.GET)
    @ResponseBody
    public Team getOne(@PathVariable("id") int id){
        for(Team team : teamList){
            if (id == team.getId()){
                return team;
            }
        }
        return null;
    }
    @RequestMapping(value = "/team/{id}",method = RequestMethod.PUT)
    @ResponseBody
    public String update(@PathVariable("id") int id,Team newTeam){
        for(Team team : teamList){
            if(team.getId()==id){
                team.setName(newTeam.getName());
                team.setLocation(newTeam.getLocation());
                return "200";
            }
        }
        return "404";
    }

    @RequestMapping(value="/team/{id}",method = RequestMethod.DELETE)
    @ResponseBody
    public String delete(@PathVariable("id") int id){
        for (Team team : teamList){
            if(team.getId()==id){
                teamList.remove(team);
                return "204";
            }
        }
        return "404";
    }

    @RequestMapping(value = "/team",method = RequestMethod.POST)
    @ResponseBody
    public String add(Team team){
        System.out.println(team);
        teamList.add(team);
        return "201";
    }
}
